<template>
  <div class="app-container">
    <!-- 按钮 -->
    <el-button type="primary" size="small" @click="onclickZhuanzhengApply">转正申请</el-button>

    <!-- 说明 -->
    <!-- <span style="padding-left: 10px;">
      <el-tag type="warning" style="padding-left: 10px;">配置说明：删除某个部门时，必须保证下属部门和当前部门人数均为0！</el-tag>
    </span> -->
    <!-- {{list}} -->
    <div style="padding: 10px;" />

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center">
        <template slot-scope="scope">
          {{ scope.row.departmentN }}
        </template>
      </el-table-column>
      <el-table-column label="岗位" align="center">
        <template slot-scope="scope">
          {{ scope.row.positionN }}
        </template>
      </el-table-column>

      <el-table-column label="主管" align="center">
        <template slot-scope="scope">
          {{ scope.row.upperN }}
        </template>
      </el-table-column>
      <el-table-column label="入职时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.ruzhiDate }}
        </template>
      </el-table-column>
      <el-table-column label="试用期" align="center">
        <template slot-scope="scope">
          {{ scope.row.shiyongqi }}
        </template>
      </el-table-column>
      <el-table-column label="转正时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.zhuanzhengDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">撤回 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <!-- 对话框 -->
    <el-dialog width="40%" :visible.sync="zhuanzhengApplyDialog.visible" top="5vh" center :show-close="false">

      <el-form ref="form" size="mini" label-position="left" label-width="100px">
        <el-row>
          <!-- 左侧 -->
          <el-col :span="11">
            <div class="title"><i class="el-icon-document" /> 申请单</div>
            <el-form-item label="转正人">
              <el-cascader v-model="zhuanzhengApplyDialog.zhuanzhengUser" :options="userList" clearable style="width: 100%;" />
            </el-form-item>
            <el-form-item label="入职时间">
              {{ ruzhiDateStr() }}
            </el-form-item>

            <el-form-item label="试用期">
              <el-select v-model="zhuanzhengApplyDialog.shiyongqi" style="width: 100%;">
                <el-option label="无试用期" value="无试用期" />
                <el-option label="一个月" value="一个月" />
                <el-option label="两个月" value="两个月" />
                <el-option label="三个月" value="三个月" />
                <el-option label="四个月" value="四个月" />
                <el-option label="五个月" value="五个月" />
                <el-option label="六个月" value="六个月" />
              </el-select>
            </el-form-item>
            <el-form-item label="转正时间">
              {{ getZhuanzhengDateStr() }}
            </el-form-item>

            <el-form-item label="部门">
              <el-select v-model="zhuanzhengApplyDialog.department" style="width: 100%;" @change="departChange">
                <el-option v-for="(item1,idx) in departmentList" :key="item1.id" :label="item1.name" :value="idx" />
              </el-select>
            </el-form-item>

            <el-form-item label="岗位">
              <el-select v-model="zhuanzhengApplyDialog.position" style="width: 100%;">
                <el-option v-for="(item2, idx) in positionList" :key="item2.id" :label="item2.name" :value="idx" />
              </el-select>
            </el-form-item>

            <el-form-item label="主管">
              <el-cascader v-model="zhuanzhengApplyDialog.upper" :options="userList" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <!-- 右侧 -->
          <el-col :span="11" :offset="2">
            <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
            <div v-for="(item,index) in zhuanzhengApplyDialog.auditors" :key="index">
              <!-- 箭头：第一个不显示 -->
              <div v-if="index>0" class="step-arrow">
                <el-row>
                  <el-col :span="8">
                    <div><i class="el-icon-caret-bottom" /></div>
                  </el-col>
                </el-row>
              </div>
              <!-- 步骤样式 -->
              <div class="step">
                <el-row>
                  <el-col :span="8">
                    <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                  </el-col>
                  <el-col :span="16">
                    <div class="step-info-right">{{ item.name }}</div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="zhuanzhengApplyDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="zhuanzhengApply">申 请</el-button>
      </div>
    </el-dialog>

    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <zhuanzheng-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { websock } from '@/websock'
const moment = require('moment')
import {
  Message
} from 'element-ui'
import { quchongAuditors } from '@/utils/utils'
import ZhuanzhengDetail from '../../components/details/zhuanzhengDetail.vue'

export default {
  components: { ZhuanzhengDetail },
  data() {
    return {
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      departmentList: null,
      positionList: null,
      userList: [],
      list: [],
      userInfo: {},
      listLoading: false,
      auditors: [],
      zhuanzhengApplyDialog: {
        visible: false,
        department: '',
        zhuanzhengUser: [],
        position: 0,
        shiyongqi: '无试用期',
        ruzhiDate: '',
        zhuanzhengDate: '',
        upper: [],
        auditors: []
      },
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async mounted() {
    this.userInfo = await websock.getUserInfo()

    websock.getDepartList().then((data) => {
      this.departmentList = data
      console.log('depart list', data)
    })
    websock.getPosList().then((data) => {
      this.positionList = data
      console.log('postion list', data)
    })

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          value: JSON.stringify({
            uid: res[i].userList[j].uid,
            name: res[i].userList[j].name,
            ruzhiDate: res[i].userList[j].ruzhiDate,
            sta: res[i].userList[j].sta
          }),
          label: res[i].userList[j].name
        })
      }
    }
    this.userList = userList

    this.auditors = await websock.getAuditors({ typ: 4 })

    this.getAuditors()

    this.getApplyRecord()
  },
  methods: {
    async getApplyRecord() {
      this.listLoading = true
      const data = await websock.zhuanzhengApplyRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      })
      this.listLoading = false
      this.list = data.list
      this.dataTotal = data.count
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getApplyRecord()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getApplyRecord()
    },
    ruzhiDateStr() {
      if (this.zhuanzhengApplyDialog.zhuanzhengUser.length === 0) return ''
      return moment(JSON.parse(this.zhuanzhengApplyDialog.zhuanzhengUser[1]).ruzhiDate).format('YYYY-MM-DD')
    },
    getZhuanzhengDateStr() {
      if (this.zhuanzhengApplyDialog.zhuanzhengUser.length === 0) return ''
      let diff = 0
      if (this.zhuanzhengApplyDialog.shiyongqi === '一个月') diff = 1
      else if (this.zhuanzhengApplyDialog.shiyongqi === '两个月') diff = 2
      else if (this.zhuanzhengApplyDialog.shiyongqi === '三个月') diff = 3
      else if (this.zhuanzhengApplyDialog.shiyongqi === '四个月') diff = 4
      else if (this.zhuanzhengApplyDialog.shiyongqi === '五个月') diff = 5
      else if (this.zhuanzhengApplyDialog.shiyongqi === '六个月') diff = 6
      return moment(JSON.parse(this.zhuanzhengApplyDialog.zhuanzhengUser[1]).ruzhiDate).add(diff, 'months').format('YYYY-MM-DD')
    },
    onclickZhuanzhengApply() {
      this.zhuanzhengApplyDialog = {
        visible: true,
        department: '',
        position: '',
        shiyongqi: '无试用期',
        ruzhiDate: '',
        zhuanzhengDate: '',
        upper: [],
        zhuanzhengUser: [],
        auditors: []
      }

      this.getAuditors()
    },
    departChange(e) {
      this.getAuditors()
    },
    // 获取审核人
    async getAuditors() {
      try {
        this.zhuanzhengApplyDialog.auditors = []
        const defaultAuditors = this.auditors.slice()

        for (let i = 0; i != defaultAuditors.length; i++) {
          if (defaultAuditors[i].sta == '1') {
            if (this.zhuanzhengApplyDialog.department === '') continue
            const departId = this.departmentList[this.zhuanzhengApplyDialog.department].id
            const lingdao = await websock.getDepartmentLingdao({ departId })
            if (lingdao.fenguan_lingdao) {
              this.zhuanzhengApplyDialog.auditors.push({ uid: lingdao.fenguan_lingdao, name: lingdao.fenguan_lingdao_name, positionName: lingdao.fenguan_lingdao_position_name })
            }
          } else if (defaultAuditors[i].sta == '0') {
            this.zhuanzhengApplyDialog.auditors.push(defaultAuditors[i])
          }
        }

        quchongAuditors(this.zhuanzhengApplyDialog.auditors)
      } catch (err) {
        console.error(err)
        this.$message.error('获取审核人失败')
      }
    },
    async zhuanzhengApply() {
      console.log(this.zhuanzhengApplyDialog)

      if (this.zhuanzhengApplyDialog.upper.length == 0) {
        return this.$message.error('请选择负责人')
      }

      if (this.zhuanzhengApplyDialog.zhuanzhengUser.length == 0) {
        return this.$message.error('请选择转正人')
      }

      if (JSON.parse(this.zhuanzhengApplyDialog.zhuanzhengUser[1]).sta == '在职') {
        return this.$message.error('已转正')
      }

      if (this.zhuanzhengApplyDialog.department === '') {
        return this.$message.error('请选择部门')
      }

      if (this.zhuanzhengApplyDialog.position === '') {
        return this.$message.error('请选择岗位')
      }

      if (this.zhuanzhengApplyDialog.auditors.length == 0) {
        return Message({
          message: '请选择审核人员',
          type: 'error',
          duration: 3 * 1000
        })
      }

      const auditors = []
      for (let i = 0; i != this.zhuanzhengApplyDialog.auditors.length; i++) {
        auditors.push({ uid: this.zhuanzhengApplyDialog.auditors[i].uid, stepName: this.zhuanzhengApplyDialog.auditors[i].stepName || this.zhuanzhengApplyDialog.auditors[i].positionName })
      }
      await websock.zhuanzhengApply({
        name: this.userInfo.name,
        ruzhiDate: this.userInfo.ruzhiDate,
        shiyongqi: this.zhuanzhengApplyDialog.shiyongqi,
        zhuanzhengDate: this.getZhuanzhengDateStr(),
        zhuanzhengUser: JSON.parse(this.zhuanzhengApplyDialog.zhuanzhengUser[1]).uid,
        zhuanzhengUserName: JSON.parse(this.zhuanzhengApplyDialog.zhuanzhengUser[1]).name,
        departmentId: this.departmentList[this.zhuanzhengApplyDialog.department].id,
        department: this.departmentList[this.zhuanzhengApplyDialog.department].name,
        positionId: this.positionList[this.zhuanzhengApplyDialog.position].id,
        position: this.positionList[this.zhuanzhengApplyDialog.position].name,
        upperId: JSON.parse(this.zhuanzhengApplyDialog.upper[1]).uid,
        upper: JSON.parse(this.zhuanzhengApplyDialog.upper[1]).name,
        auditors
      })

      this.zhuanzhengApplyDialog.visible = false

      this.getApplyRecord()
    },
    async revertApply(idx) {
      try {
        await websock.revertZhuanzhengApply({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    },
    printPdf(id) {
      websock.printPdf({ typ: 4, id }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import url("../../styles/form.css");
</style>
